package main

import (
	"gitee.com/rainbowserver_go/task"
	"github.com/fatih/color"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
)

const process = "rainbowserver.js"
const startServerSh = "start_rainbow_server_shell.sh"

func start(isRestart bool) {
	findCmd := "url=`find ~/rainbow -name " + startServerSh + "`"
	filename := "start_rainbow"
	shellContent := `#!/bin/bash
` + findCmd + `
cd ${url%/*}
./${url##*/}
#$url
`
	var f *os.File
	f, _ = os.Create(filename)
	io.WriteString(f, shellContent)

	cmd := exec.Command("chmod", "a+x", filename)
	cmd.Start()

	time.Sleep(time.Second / 2)

	cmd = exec.Command("sh", "-C", "start_rainbow")
	cmd.Start()

	if !isRestart {
		color.Green("====================")
		color.Green("=  服务已成功开启  =")
		color.Green("====================")
	} else {
		color.Green("====================")
		color.Green("=   服务重启成功   =")
		color.Green("====================")
	}
}

func stop() {
	pid := getPid()
	cmd := exec.Command("kill", "-9", pid)
	cmd.Start()
}

func restart() {
	stop()
	time.Sleep(time.Second / 2)
	start(true)
}

func getPid() string {
	filename := "get_rainbow_pid"
	ps_cmd := "`ps -ef |grep \"" + process + "\"|grep -v grep | awk '{print $2}'`"
	shellContent := `#!/bin/bash
PIDS=` + ps_cmd + `
echo $PIDS	
`

	var f *os.File
	f, _ = os.Create(filename)
	io.WriteString(f, shellContent)

	cmd := exec.Command("chmod", "a+x", filename)
	cmd.Start()

	time.Sleep(time.Second / 2)

	cmd2 := exec.Command("sh", "-C", filename)
	stdout, err := cmd2.StdoutPipe()

	defer stdout.Close()
	if err := cmd2.Start(); err != nil {
		log.Fatal(err)
	}

	opBytes, err := ioutil.ReadAll(stdout)
	if err != nil {
		log.Fatal(err)
	}

	return strings.Replace(strings.Trim(string(opBytes), ""), "\n", "", -1)
}

func main() {
	carGameTask := new(task.CarGameTask)
	carGameTask.Init()
	carGameTask.Start()

	/*can := true
	if len(os.Args) > 1 {
		action := os.Args[1]
		if action != "start" && action != "stop" && action != "restart" && action != "api" {
			can = false
		} else {
			pid := getPid()
			pidCount := strings.Count(pid, "")
			if action == "start" {
				if pidCount > 1 {
					color.Red("服务已经开启，请勿重复开启！PID：" + pid)
				} else {
					start(false)
				}
			} else if action == "stop" {
				if pidCount <= 1 {
					color.Red("服务并未开启，无须停止！")
				} else {
					stop()
				}
			} else if action == "restart" {
				restart()
			} else if action == "api" {
				api := new(webapi.Api)
				api.Start()
			}
		}
	} else {
		can = false
	}

	if can == false {
		color.Red("参数错误，请输入（start、stop、restart或api）")
	}*/
}
